package com.crdeng.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crdeng.handler.BusinessException;
import com.crdeng.response.Result;
import com.crdeng.response.ResultCode;
import com.crdeng.system.entity.Menu;
import com.crdeng.system.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author crdeng
 * @since 2020-11-27
 */

@Api(value = "菜单模块", tags = "菜单模块")
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @ApiOperation(value = "获取所有菜单")
    @GetMapping("/getMenu")
    public Result getMenu() {
        List<Menu> list = menuService.list();
        return Result.ok().data("list", list);
    }

    @ApiOperation(value = "获取菜单树")
    @GetMapping("/getMenuTree")
    public Result getMenuTree() {
        List<Menu> list = menuService.getMenuTree();
        return Result.ok().data("list", list);
    }

    @ApiOperation(value = "删除菜单", notes = "使用ID删除菜单")
    @GetMapping("/deleteMenuById")
    public Result deleteMenuById(@RequestParam Long id) {
        boolean flag = menuService.removeById(id);
        if (!flag) {
            throw new BusinessException(ResultCode.MENU_NOT_EXIST.getCode(), ResultCode.MENU_NOT_EXIST.getMessage());
        }
        return Result.ok().message("删除菜单成功");
    }


    @ApiOperation(value = "添加菜单", notes = "添加菜单")
    @PostMapping("/addMenu")
    public Result addMenu(@RequestBody Menu menu) {
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
                menuQueryWrapper.eq("menu_name",menu.getMenuName());
        Menu isMenu = menuService.getOne(menuQueryWrapper);

        /*判断是否已经存在菜单*/
        if (isMenu != null) {
            throw new BusinessException(ResultCode.MENU_ALREADY_EXIST.getCode(), ResultCode.MENU_ALREADY_EXIST.getMessage());
        }

        menu.setId(null);
        Date date = new Date();
        menu.setCreateTime(date);
        menu.setModifiedTime(date);
        boolean flag = menuService.save(menu);
        if (!flag) {
            throw new BusinessException(ResultCode.MENU_ADD_FAIL.getCode(), ResultCode.MENU_ADD_FAIL.getMessage());
        }
        return Result.ok().message("添加菜单成功");

    }


    @ApiOperation(value = "编辑菜单", notes = "编辑菜单")
    @PostMapping("/editMenu")
    public Result editMenu(@RequestBody Menu menu) {
        menu.setModifiedTime(new Date());
        boolean flag = menuService.updateById(menu);
        if (!flag){
            throw  new BusinessException(ResultCode.MENU_EDIT_FAIL.getCode(),ResultCode.MENU_EDIT_FAIL.getMessage());
        }
         return Result.ok().message("编辑菜单成功");

    }


}

